var express = require("express");
var router = express.Router();
const { generateToken } = require("../../utils/jwt");
const Result = require("../../utils/result");
var fs = require("fs");
const multer = require("multer");
const upload = multer({ dest: "public/images/admin/" }); // 文件储存路径

router.post('/login',async function (req, res){
    const user = req.body;
    if(user.username != 'admin' || user.password != 'Cwy123456'){
        throw new Error("用户名或者密码不正确");
    }
    const token = generateToken(user);
    res.json(Result.success({token}));
});

// 上传图片
router.post("/uploadImg", upload.single("file"), function (req, res, next) {
    try {
      let file = req.file;
      const oldPath = file.destination + file.filename;
      const type = file.mimetype.split("/")[1];
      const fileFullname = file.filename + "." + type;
      const newPath = "public/images/admin/" + fileFullname;
      // 修改文件名，为文件加上后缀
      fs.rename(oldPath, newPath, function (err) {
        if (err) {
          throw err;
        }
      });
      // 返回静态资源地址
      const imageUrl = "http://localhost:8080/images/admin/" + fileFullname;
      res.json(Result.success({ imageUrl }));
    } catch (error) {
      res.json(Result.fail(error));
    }
  });

module.exports = router;
